package postpc.powerreminders.com.systemEvents;

import java.util.List;

import postpc.powerreminders.com.db.RotgDatabase;
import postpc.powerreminders.com.events.RotgEventManager;

import android.app.ActivityManager;
import android.app.ActivityManager.RunningAppProcessInfo;
import android.app.ActivityManager.RunningServiceInfo;
import android.app.KeyguardManager;
import android.content.Context;
import android.database.Cursor;
import android.os.Handler;
import android.util.Log;


public class SystemEvents{

	private static final String TAG = "ROTG_SYS_EVENTS";

	private static final long EVENTS_TIMER_DELAY = 5000;

	/*
	 * Periodic timer update
	 */
	Handler handler = new Handler();

	/*
	 * Handler to the Android activity manager. 
	 */
	ActivityManager activityManager;

	/*
	 * Save the running tasks at startup
	 */
	List<RunningAppProcessInfo> startupRunningTasks;

	/*
	 * Reference to the Event Manager. 
	 */
	RotgEventManager eventManager;

	/*
	 * Reference to the database.
	 */
	RotgDatabase dataBase;

	/*
	 * Reference to the main activity context for user alerts and services. 
	 */
	Context context;

	/**
	 * 
	 * @param context
	 */
	public SystemEvents(RotgEventManager em, RotgDatabase db, Context context){
		Log.i(TAG, "Initializing system events manager");
		
		this.eventManager = em;
		this.dataBase = db;
		this.context = context;
		
		this.activityManager = (ActivityManager) this.context.getSystemService(Context.ACTIVITY_SERVICE);
		startupRunningTasks = activityManager.getRunningAppProcesses();

		handler.postDelayed(servicesTimedTask, EVENTS_TIMER_DELAY);
	}

	/**
	 * 
	 */
	public void checkRunningApplications(){

		KeyguardManager kgMgr = (KeyguardManager) this.context.getSystemService(Context.KEYGUARD_SERVICE);
		boolean showing = kgMgr.inKeyguardRestrictedInputMode();
		
		if (showing){
			Log.i(TAG, "Screen is locked");
			handler.postDelayed(servicesTimedTask, EVENTS_TIMER_DELAY);
			return;
		}
		
		List<RunningAppProcessInfo> runningTasks = activityManager.getRunningAppProcesses();

		for (RunningAppProcessInfo info: runningTasks){
			boolean found = true;
			for (RunningAppProcessInfo startup: this.startupRunningTasks){
				if (0 == startup.processName.compareTo(info.processName)){
					found = false;
				}
			}
			
			// Found a new application
			if (found){
				Log.i(TAG, "Found new process :" + info.processName);
				Cursor cursor = this.dataBase.checkApplication(info.processName);
				if (0 != cursor.getCount()){
					// ALERT
					this.eventManager.notifyReminderEvent(cursor.getString(2));
					this.dataBase.deactivateReminder(cursor.getInt(0));
				}
			}
		}	
		
		handler.postDelayed(servicesTimedTask, EVENTS_TIMER_DELAY);
	}

	/**
	 * 
	 */
	public void checkRunningServices(){
		java.util.List<RunningServiceInfo> mserviceTasks;

		mserviceTasks = activityManager.getRunningServices(100);
		for (RunningServiceInfo serinfo : mserviceTasks) {
			Log.i(TAG, serinfo.process+"("+serinfo.pid+")");            
		}
	}

	/**
	 * Task Handler for the watch dog 
	 */
	public Runnable servicesTimedTask = new Runnable() {
		public void run() {
			Log.i(TAG, "get services Called");
			checkRunningApplications();
		}
	};

	public void onDestroy() {
		Log.i(TAG, "Destroing system events");
		handler.removeCallbacks(servicesTimedTask);
	}
}
